﻿/// <Reference Name="MicrosoftAjax.js" />

(function () {

    function execute() {

        Type.registerNamespace('Toolkit');

        Toolkit.Data = function () {
            /// <summary>Toolkit.UI static class</summary>
            throw 'Static class does not have any instance';
        }

        Toolkit.Data.addItem = function (item, listName, callback) {
            /// <summary>Add item to list</summary>
            /// <param name="item" type="Object" optional="false" mayBeNull="false">Item</param>
            /// <param name="listName" type="String" optional="false" mayBeNull="false">List name</param>
            /// <param name="callback" type="Function" optional="false" mayBeNull="false">Callback</param>
            var e = Function.validateParameters(arguments, [{ name: 'item', type: Object, optional: false, mayBeNull: false },
                                                            { name: 'listName', type: String, optional: false, mayBeNull: false },
                                                            { name: 'callback', type: Function, optional: false, mayBeNull: false }], true);
            if (e) throw e;

            var clientContext = SP.ClientContext.get_current();
            var spList = clientContext.get_web().get_lists().getByTitle(listName);
            var itemCreateInfo = new SP.ListItemCreationInformation();
            var spListItem = spList.addItem(itemCreateInfo);
            for (var field in item) {
                if (item.hasOwnProperty(field) === true) {
                    spListItem.set_item(field, item[field]);
                }
            }
            spListItem.update();
            clientContext.load(spListItem);
            clientContext.executeQueryAsync(function () {
                callback(spListItem);
            }, function (sender, args) {
                alert(args.get_message());
            });
        }

        Toolkit.Data.registerClass('Toolkit.Data');
    }

    if (window.Sys && Sys.loader) {
        Sys.loader.registerScript('Data', null, execute);
    }
    else {
        execute();
    }

})();